package edu.gxmzu.task.service.impl;

import edu.gxmzu.task.mapper.ReportManagementMapper;

import edu.gxmzu.task.models.ReportManagementModel;
import edu.gxmzu.task.models.ReportWorkModel;
import edu.gxmzu.task.models.ReportWorkStatusCountModel;
import edu.gxmzu.task.service.ReportManagementService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportManagementServiceImpl implements ReportManagementService {
    @Autowired
    private ReportManagementMapper reportManagementMapper;

    public List<ReportManagementModel> getReport(Long createTime, Long endTime, String title) {
        if (title!=null&&createTime==null){
            createTime = 0L;
        }

        if (createTime == null && endTime == null) {
            // 获取当前时间
            ZonedDateTime now = ZonedDateTime.now();
            // 获取本周周一的日期
            ZonedDateTime startOfWeek = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
                    .truncatedTo(java.time.temporal.ChronoUnit.DAYS)
                    .withHour(0)
                    .withMinute(0)
                    .withSecond(0)
                    .withNano(0);

            // 将ZonedDateTime转换为时间戳
            Instant instant = startOfWeek.toInstant();
            createTime = instant.toEpochMilli();
        }

        List<ReportWorkModel> workStatusList = reportManagementMapper.getReport(createTime,endTime,title);
        // 使用Map来合并数据
        Map<Long, List<ReportWorkStatusCountModel>> mergedMap = new HashMap<>();
        for (ReportWorkModel model : workStatusList) {
            List<ReportWorkStatusCountModel> countList = mergedMap.computeIfAbsent(model.getCreateTime(), k -> new ArrayList<>());
            ReportWorkStatusCountModel existingCount = countList.stream()
                    .filter(wc -> wc.getWorkStatusId().equals(model.getWorkStatusId()))
                    .findFirst()
                    .orElse(new ReportWorkStatusCountModel(model.getWorkStatusId(), 0));
            existingCount.setCount(existingCount.getCount() + model.getCount());
            countList.removeIf(wc -> wc.getWorkStatusId().equals(model.getWorkStatusId()) && wc.getCount() == 0); // 移除计数为0的项（可选）
            if (!countList.contains(existingCount)) {
                countList.add(existingCount);
            }

        }
        // 将Map转换为List<MergedReportWorkStatusModel>
        List<ReportManagementModel> mergedList = mergedMap.entrySet().stream()
                .map(entry -> new ReportManagementModel(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());

        return mergedList;
    }

}
